package longfly.development;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class Day_Check extends Activity {
    /** Called when the activity is first created. */

	TextView	TEST,DAYCHECK_TIME,MONTHCHECK_TIME;
	Button		DAY_CHECK_BTN_1,DAY_CHECK_BTN_2,MONTH_CHECK_BTN_1,MONTH_CHECK_BTN_2;
	Button		TEST_EXIT;
	boolean		DAY_OR_MONTH;
  	//定义SharedPreferences对象  
	SharedPreferences settings; 
	String	SPF_Pos_DayCheck_Time		=	"SPF_Pos_DayCheck_Time";
	String	SPF_Pos_MonthCheck_Time		=	"SPF_Pos_MonthCheck_Time";
	String	SPF_Pos_DayCheck_Data		=	"SPF_Pos_DayCheck_Data";
	String	SPF_Pos_MonthCheck_Data		=	"SPF_Pos_MonthCheck_Data";

	ProgressDialog progressDialog;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.i800_day_check);
        
       find_id();
       key_things();
	   settings = getSharedPreferences("POS_Setup_SharedPreferences", 0);		
       //刷新上次日结时间
       init_last_check_time();
	}

	private void init_last_check_time() {
		// TODO Auto-generated method stub
        get_SharePerference();   
	}

	private void get_SharePerference() {
		try {
			DAYCHECK_TIME.setText(  settings.getString(SPF_Pos_DayCheck_Time, null) );
		} catch (Exception e) {
			// TODO: handle exception
			DAYCHECK_TIME.setText(  "未做过日结" );
		}	
		
		try {
			MONTHCHECK_TIME.setText(  settings.getString(SPF_Pos_MonthCheck_Time, null) );
		} catch (Exception e) {
			// TODO: handle exception
			MONTHCHECK_TIME.setText(  "未做过月结" );
		}	
	}
	
	private void key_things() {
		DAY_CHECK_BTN_1.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		//判断今天有没有日结过！
		   		//1.获取今天的日期
		   		String Now_Data = init_time(2);
		   		//2.对比上一次日结的时间
		   		String Last_Data =  settings.getString(SPF_Pos_DayCheck_Data, null) ;
		   		//4.今天的日期比对比的大一天，则进行日结
		   	//设定时间的模板
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
				//得到指定模范的时间
				boolean Not_dayCheck = false;
				Date dnow = null,dlast = null;
				try {
					dnow = sdf.parse(Now_Data);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

				try {
					dlast = sdf.parse(Last_Data);
				} catch (ParseException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					
				}
				Not_dayCheck = Math.abs(dnow.getTime() - dlast.getTime()) >0;

		   		if (Not_dayCheck) {			   		
			   		DAY_OR_MONTH = true;
					progressDialog("正在日结处理 ", "请稍等......");		
			     	insert_Thread thread= new insert_Thread();
			     	thread.start();						
				} else {
					//提示今天已经日结过了
					Toast.makeText(Day_Check.this, "今天已经日结过了 ",Toast.LENGTH_SHORT).show();
				}

		   	}
	    });	

		DAY_CHECK_BTN_2.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
				Intent intent_page_new = new Intent();
				intent_page_new.setClass(Day_Check.this, Day_Check_DishSell.class);			
				startActivity(intent_page_new);	
				overridePendingTransition(R.anim.zoomin, R.anim.zoomout);
		   	}
	    });	
		
		MONTH_CHECK_BTN_1.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		DAY_OR_MONTH = false;
				progressDialog("正在月结处理 ", "请稍等......");		
		     	insert_Thread thread= new insert_Thread();
		     	thread.start();	
		   	}
	    });	
		
		MONTH_CHECK_BTN_2.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
				progressDialog("正在月结处理 ", "请稍等......");		
		     	insert_Thread thread= new insert_Thread();
		     	thread.start();	
		   	}
	    });	
		TEST_EXIT.setOnClickListener(new Button.OnClickListener()
	    {
		   	@Override
		   	public void onClick(View v)
		   	{	
		   		finish();
		   	}
	    });			
		
	}

	
	private void find_id() {
		// TODO Auto-generated method stub
		TEST		=	(TextView) findViewById(R.id.about_test);
		DAYCHECK_TIME	=	(TextView) findViewById(R.id.day_check_time_text);
		MONTHCHECK_TIME	=	(TextView) findViewById(R.id.month_check_time_text);
		DAY_CHECK_BTN_1	=	(Button) findViewById(R.id.day_check_btn_1);
		DAY_CHECK_BTN_2	=	(Button) findViewById(R.id.day_check_btn_2);
		MONTH_CHECK_BTN_1	=	(Button) findViewById(R.id.month_check_btn_1);
		MONTH_CHECK_BTN_2	=	(Button) findViewById(R.id.month_check_btn_2);
		TEST_EXIT	=	(Button) findViewById(R.id.other_setup_exit);
	}

	// 1是全格式日期时间   2是日期  3是时间
    private String init_time(int choose) {
		// TODO Auto-generated method stub
    	int mYear,mMonth,mDay,mHour,mMinute,mSecond;

    	//获取桌台号和即时时间    
   		final Calendar c = 	Calendar.getInstance();
        mYear	= c.get(Calendar.YEAR); 	//获取当前年份
        mMonth 	= c.get(Calendar.MONTH)+ 1;	//获取当前月份
        mDay 	= c.get(Calendar.DAY_OF_MONTH);//获取当前月份的日期号码
        mHour 	= c.get(Calendar.HOUR_OF_DAY);//获取当前的小时数
        mMinute = c.get(Calendar.MINUTE);	//获取当前的分钟数		   		
        mSecond = c.get(Calendar.SECOND);	//获取当前的秒钟数		   		

   		String mmHour,mmMinute,mmSecond;

   		if(mHour < 10)
   			mmHour = "0"+mHour;
   		else
   			mmHour = ""+mHour;

   		if(mMinute < 10)
   			mmMinute = "0"+mMinute;
   		else
   			mmMinute = ""+mMinute;

   		if(mSecond < 10)
   			mmSecond = "0"+mSecond;
   		else
   			mmSecond = ""+mSecond;

   		String Reback = null ;
   		String	system_date	= mYear+"-"+mMonth+"-"+	mDay;
   		String	system_time	= mmHour+":"+mmMinute+":"+mmSecond;	
   		
   		switch (choose) {
		case 1:
	   		Reback = system_date +"  "+ system_time;
			break;
		case 2:		
	   		Reback = system_date;
			break;
		case 3:
	   		Reback = system_time;		
			break;		
		default:
			break;
		}

 		return Reback ;
	}
	
	/***************     以下是一个带进度条的对话框    **************************************/
	private void progressDialog(String title, String message) {
		// TODO Auto-generated method stub
	     progressDialog = new ProgressDialog(Day_Check.this);
	     progressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
	     progressDialog.setMessage(message);
	     progressDialog.setTitle(title);
	     progressDialog.setProgress(0);
	     progressDialog.setMax(100);
	     progressDialog.setCancelable(false);
	     progressDialog.show();
	}

	//用来查询进度条的值！大于100就把进度条Cancel掉
    Handler handler = new Handler(){
    	  @Override
    	  public void handleMessage(Message msg) {
    		  // TODO Auto-generated method stub
    		  if(msg.what>=100){
   		       	  init_last_check_time();
    			  progressDialog.cancel();
    	       }
    		  progressDialog.setProgress(msg.what);
    		  super.handleMessage(msg);
    	  }
    };

	
//创建一个进程！用来后台加载数据
    class insert_Thread extends Thread{
        public void run(){	 
			handler.sendEmptyMessage(1);	//进度条进度	
			//获取时间
        	String Check_Time = init_time(1);
	        //获得SharedPreferences 的Editor对象  
	        SharedPreferences.Editor editor = settings.edit();          	
    	
        	if (DAY_OR_MONTH) {
				//日结
    			handler.sendEmptyMessage(10);	//进度条进度	
    			//统计今天的菜品销售数量
    			Sum_Today_DishSell();
    			handler.sendEmptyMessage(20);	//进度条进度	
    			//合并今天的销售额
    			//统计利润
    			//菜品销售排名
    			
    			
    			
    			
    			
    			//把时间写入上次日结时间
    	        editor.putString(SPF_Pos_DayCheck_Time, String.valueOf( Check_Time ));  
    	        editor.putString(SPF_Pos_DayCheck_Data, String.valueOf( init_time(2) ));  
    			handler.sendEmptyMessage(90);	//进度条进度	           		
			} else {
				//月结
				handler.sendEmptyMessage(10);	//进度条进度	
				
    			//把时间写入上次月结时间				
    	        editor.putString(SPF_Pos_MonthCheck_Time, String.valueOf( Check_Time ));  
    	        editor.putString(SPF_Pos_MonthCheck_Data, String.valueOf( init_time(2) ));  
				handler.sendEmptyMessage(90);	//进度条进度	   
			}
	        editor.commit();    	//很重要！用于保存数据！不用commit保存是写不进文件的！     	
			handler.sendEmptyMessage(100);	//进度条进度	   
			
        }
    }
	
	/***************     以上是一个进度条    **************************************/


    //统计当天的菜品销售，生成当天的菜品销售屏排名，销售数量，销售额
    public void Sum_Today_DishSell() {
    	// TODO Auto-generated method stub
    	SQLiteDatabase db;
  	    db = SQLiteDatabase.openOrCreateDatabase(this.getFilesDir().toString()+"/Android_POS.db3", null);
	
    	int mYear,mMonth,mDay;

    	//获取桌台号和即时时间    
   		final Calendar c = 	Calendar.getInstance();
        mYear	= c.get(Calendar.YEAR); 	//获取当前年份
        mMonth 	= c.get(Calendar.MONTH)+ 1;	//获取当前月份
        mDay 	= c.get(Calendar.DAY_OF_MONTH);//获取当前月份的日期号码
        
   		String	start_time	= mYear+"-"+mMonth+"-"+	mDay+" "+"00:00";
   		String	end_time	= mYear+"-"+mMonth+"-"+	mDay+" "+"23:59";

   		String[] refer = {start_time , end_time};
		Cursor  cursor = db.rawQuery("select * from lfcy_base_sellinf where dXiadantime > ? and dXiadantime < ? ",refer);
		//获取到了时间段内所有菜品
		while(cursor.moveToNext()) {
			String item  = cursor.getString(cursor.getColumnIndex("cDishCode"));
   			sql_control sqlc = new sql_control();					
			boolean if_only_one = sqlc.sql_item_only_one(db, "lfcy_day_check_dish", "cDishCode", item);
			//先判断这个菜是不是有了！
			if (if_only_one) {
				//没有重复
				
				//获取数量
		   	    Integer Dishnum = new Integer(cursor.getString(cursor.getColumnIndex("cDishQty")));
				//获取总价格
		   	    float DishAllPrice = Float.parseFloat(cursor.getString(cursor.getColumnIndex("fDishPrice")));
				//得到单价
		   	    float DishPrice = DishAllPrice/Dishnum;
		   	    
		   	    
				//插入数据
				db.execSQL("insert into lfcy_day_check_dish values(null,?,?,?,?,?,?,?,?,null)", 
						new String[]{
					mYear+"-"+mMonth+"-"+mDay,	
					cursor.getString(cursor.getColumnIndex("cDishName")) ,
					cursor.getString(cursor.getColumnIndex("cDishCode")) ,	
					""+DishPrice ,
					cursor.getString(cursor.getColumnIndex("cDishQty")) ,
					cursor.getString(cursor.getColumnIndex("cDishUnitName")) ,
					cursor.getString(cursor.getColumnIndex("cDishUnitCode")) ,
					cursor.getString(cursor.getColumnIndex("fDishPrice"))				
				});
			} else {
				//重复了
				//updata数据
		   		try {
		   			ContentValues cv = new ContentValues();
		   		   	//存储修改的数据
		   		   	cv.put("cDishName" 		, cursor.getString(cursor.getColumnIndex("cDishName")));
		   		   	cv.put("cDishCode" 		, cursor.getString(cursor.getColumnIndex("cDishCode")));
		   		   	cv.put("fDishPrice" 	, cursor.getString(cursor.getColumnIndex("fDishPrice")) );
		   		   	cv.put("cDishUnitName" 	, cursor.getString(cursor.getColumnIndex("cDishUnitName")) );
		   		   	cv.put("cDishUnitCode" 	, cursor.getString(cursor.getColumnIndex("cDishUnitCode")) );
		   		   	String[] fuc = {item};
		   		    Cursor cursor2 = db.rawQuery("select * from lfcy_day_check_dish where cDishCode = ?",fuc);
		   		    String recorsend = "null",price_thiscaiist = "null";
		   		    while(cursor2.moveToNext()) {
						recorsend  = cursor2.getString(cursor2.getColumnIndex("cDishQty"));
						price_thiscaiist  = cursor2.getString(cursor2.getColumnIndex("fDishPrice"));
					}
			   	    Integer intObjj = new Integer(recorsend);
			   	    int qty_i = intObjj	;	//刚才已有的  
			   	    float qty_f = Float.parseFloat(price_thiscaiist);
			   	    
			   		Integer intObj = new Integer(cursor.getString(cursor.getColumnIndex("cDishQty")));
			   	    int qty_j = intObj;		//新的一条
			   	    float qty_k = Float.parseFloat(cursor.getString(cursor.getColumnIndex("fDishPrice")));

		   		   	cv.put("cDishQty" 		, qty_i + qty_j );
		   		   	cv.put("fDishAllPrice" 	, qty_f + qty_k );
		   		   	String[] contion = {item}; 
				   	db.update("lfcy_day_check_dish",cv,"cDishCode = ? ",contion);
		   		} catch (Exception e) {
					System.out.println("update failed");					   									
		   		}	
			}

		}		
    	
    };

  
    
}